<?php

class Main extends CI_Controller {
	
	var $data = array();
	
	public function __construct()
	{
		parent::__construct();
		
		$this->data['seo_title'] = '';
		$this->data['seo_description'] = '';
		$this->data['seo_keywords'] = '';
		
		// incarcam formularul de login doar daca utilizatorul nu este conectat
		if(!$this->session->userdata('is_logged_in')) {
			$login = $this->load->view('login', '', true);
			$this->data['login'] = $login;
		}
	}
	
	public function index()
	{	
		$this->load->view('general/header', $this->data);
		$this->load->view('home', $this->data);
		$this->load->view('general/footer', $this->data);
	}
	
	public function login()
	{
		$this->load->view('general/header', $this->data);
		$this->load->view('login');
		$this->load->view('general/footer', $this->data);
	}
	
	public function register()
	{
		$this->load->view('general/header', $this->data);
		$this->load->view('register');
		$this->load->view('general/footer', $this->data);
	}
	
	public function forgot()
	{
		$this->load->view('general/header', $this->data);
		$this->load->view('forgot');
		$this->load->view('general/footer', $this->data);
		
		if($this->input->post('email')) {
			$this->load->library('form_validation');
			$this->load->model('model_users');
			$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
			
			if($this->form_validation->run()) {		
				if($key = $this->module_users->valid_email()) {
					$this->load->library('email', array('mailtype'=>'html'));
					$this->email->from('me@mywebsite.com', 'Ionut');
					$this->email->to($this->input->post('email'));
					$this->email->subject("Recuperare parola");
					
					$message = "<p> Multumim pentru inregistrare.</p>";
					$message .= "<p><a href='".base_url()."main/change_pass/$key"."'> Click aici</a> pentru a va modifica parola.</p>";
					
					$this->email->message($message);
				}
			} else {
				echo "problema";
			}
		}
	}
	
	public function members($page='',$subpage='') {
		$this->load->model('model_users');
		
		$this->load->view('general/header', $this->data);
		if($this->session->userdata('is_logged_in')) {
			$data=$this->model_users->get_data($this->session->userdata('email'));
			if(!isset($page)||$page=='') {
				if($data['user_type']==0 || $data['user_type']==1) {
					$data['sel']='profile';
					$this->load->view('members_menu',$data);
					
					// extragem din bd autorizatiile utilizatorului
					$this->load->model('model_auth');
					$data['auth'] = $this->model_auth->get_user_auth($data['id']);
					
					$this->load->view('profile',$data);
				} else if($data['user_type']==3) {
					redirect('admin/users');
				}
			} elseif($page == 'activitate') {
				$this->load->model('model_activity');
				$data['top'] = $this->model_activity->get_top_parking($data['id']);
				$data['latest'] = $this->model_activity->get_latest_activity($data['id'],$data['user_type']);
				$data['sel']='activity';

				$this->load->view('members_menu', $data);
				$this->load->view('activity', $data);
			} elseif($page == 'plati') {
				$data['sel']='payments';
				$this->load->view('members_menu', $data);
				$this->load->view('payments');
			}
		} else {
			redirect('main/index');
		}
		$this->load->view('general/footer', $this->data);
	}
	
	public function auth_save() {
		if($this->session->userdata('is_logged_in')) {
			$this->load->library('form_validation');
			
			$config['upload_path'] = './uploads/';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size']	= '2000';
			$config['max_width']  = '1024';
			$config['max_height']  = '768';
			
			$this->form_validation->set_rules('auth_no', 'Numar autorizatie', 'required|trim|xss_clean');
			$this->form_validation->set_rules('valability', 'Valabilitate', 'required|trim|xss_clean');
			$this->form_validation->set_rules('ora_start', 'Ora start', 'required|trim|xss_clean');
			$this->form_validation->set_rules('ora_end', 'Ora end', 'required|trim|xss_clean');
			
			if($this->form_validation->run()) { 
				$this->load->library('upload', $config);
				if ( $this->upload->do_upload()) {
					$upload_data = $this->upload->data();
				}
				$this->load->model('model_auth');
				if($this->model_auth->add_auth($this->input->post('uid'),$this->input->post('utype'))) {
					redirect('main/members/profil');
				} else {
					redirect('main/members/profil');
				}
				
			}
		} else {
			redirect('/');
		}
	}
	
	public function profile_save() {
		if($this->session->userdata('is_logged_in')) {
			$this->load->library('form_validation');
			$this->load->model('model_users');
			
			// validare formular
			$this->form_validation->set_rules('pass', 'Parola', 'required|trim');
			$this->form_validation->set_rules('cpass', 'Confirma Parola', 'required|trim|matches[pass]');
			
			if($this->form_validation->run()) {
				if($this->model_users->update_user($this->session->userdata('email'))) {
					redirect('main/members/profil');
				} else {
					redirect('main/members/profil');
				}
			} else {
				redirect('main/members/profil');
			}
		} else {
			redirect('/');
		}
	}
	
	public function login_validation($email1='',$pass1='') 
	{	
		$this->load->view('general/header', $this->data);
		$this->load->library('form_validation');
		$ok=false;
		if($email1=='' && $pass1=='') {
			$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|callback_validate_credentials');
			$this->form_validation->set_rules('pass', 'Parola', 'required|trim');
		} else {
			$email1=urldecode($email1);
			$ok=$this->validate_credentials($email1,$pass1);
		}
		
		if($this->form_validation->run()||$ok){
			if($ok==false) {
				$data = array(
					'email' => $this->input->post('email'),
					'is_logged_in' => 1
				);
			} else {
				echo 'yes';
				die();
			}
			$this->session->set_userdata($data);
			redirect('main/members');	
		} else {
			if($email1=='') {
				$this->load->view('login');
			} else {
				echo 'no';
				die();
			}
		}
		$this->load->view('general/footer', $this->data);

	}
	
	public function register_validation($email='',$pass='',$cpass='')
	{
		$this->load->library('form_validation');
		$this->load->model('model_users');
		
		if($email==''&&$pass==''&&$cpass=='') {
			// validare formular
			$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[users.email]');
			$this->form_validation->set_rules('pass', 'Parola', 'required|trim');
			$this->form_validation->set_rules('cpass', 'Confirma Parola', 'required|trim|matches[pass]');
			
			// suprascriere mesaje de eroare
			$this->form_validation->set_message('is_unique', "Adresa de email exista deja!");
		} 
		
		if($this->form_validation->run()||($email!=''||$pass!='')) {
		
			// generare cheie random	
			$key = md5(uniqid().time());
			
			$this->load->library('email', array('mailtype'=>'html'));
			$this->email->from('contact@parking.ro', 'Parking.ro');
			if($email!='') {
				$email=urldecode($email);
				$this->email->to($email);
			} else {
				$this->email->to($this->input->post('email'));
			}
			$this->email->subject("Confirmare cont");
			
			$message = "<p> Multumim pentru inregistrare.</p>";
			$message .= "<p><a href='".base_url()."main/confirm_user/$key"."'> Click aici</a> pentru a confirma contul.</p>";
			
			$this->email->message($message);
			
			// trimite email utilizatorului
			// adaugare utilizator in tabela temporara
			if($this->model_users->add_temp_user($email,$pass,$key)) {
				if($this->email->send()) {
					if($email!=''||$pass!='') {
						echo 'ok';
						die();
					}
						
					$this->load->view('general/header');
					$data['error'] = "Va rugam sa verificati adresa de email pentru a va confirma contul.";
					$this->load->view('register',$data);
					$this->load->view('general/footer');
				} else {
					if($email!=''||$pass!='') {
						echo 'error';
						die();
					}
					$this->load->view('general/header');
					$data['error'] = "Trimiterea mesajului de confirmare a esuat.";
					$this->load->view('register',$data);
					$this->load->view('general/footer');
				}
			} else {
				$this->load->view('general/header');
				$data['error'] = "Adaugarea in baza de date a esuat.";
				$this->load->view('register',$data);
				$this->load->view('general/footer');
			}
		} else {
			$this->load->view('general/header');
			$data['error']="Informatii nu au fost completate corect!";
			$this->load->view('register',$data);
			$this->load->view('general/footer');
		}
	}
	
	public function validate_credentials($email1='',$pass1='')
	{
		$this->load->model('model_users');

		if($this->model_users->login_ok($email1,$pass1)) {
			return true;
		} else {
			$this->form_validation->set_message('validate_credentials', 'Email / parola incorect. ');
			return false;
		}
	}
	
	public function logout() 
	{
		$this->session->sess_destroy();
		redirect('main/index');
	}
	
	public function confirm_user($key) 
	{
		$this->load->module('module_users');
		
		if($this->module_users->is_key_valid($key)){
			if($newemail = $this->model_users->add_user($key)) {
				$data = array(
					$email => $newemail,
					'is_logged_in' => 1
				);
				
				$this->session->set_userdata($data);
				redirect('main/members');
			} else {
				$this->load->view('general/header');
				$data['error'] = "Confirmarea contului nu a putut fi realizata!";
				$this->load->view('register',$data);
				$this->load->view('general/footer');
			}
		} else {
			$this->load->view('general/header');
			$data['error'] = "Cheia de confirmare este invalida.";
			$this->load->view('register',$data);
			$this->load->view('general/footer');
		}
	}
	
	public function get_parking($lat='',$long='') {
		$this->load->model('model_auth');
		$data = $this->model_auth->get_proximity($lat,$long);
		echo json_encode($data);
	}
	
	public function cron() {
		$this->db->query("update authorizations a
				inner join
				(select auth_id, count(*) as 'expired_places' from not_available where status=1 and (start_hour + Interval period*60 minute)<now()
				group by auth_id) na
				on a.id=na.auth_id
				set a.available=a.available+na.expired_places");

		$this->db->query("update not_available set status=0 where status=1 and (start_hour + Interval period*60 minute)<now()");
	}
	
	public function update_stay($auth_id='') {
		$this->db->query("update authorizations set available=available-1 where id='".$auth_id."'");
		$this->db->query("INSERT INTO `parcari`.`not_available` (`id`, `auth_id`, `user_id`, `start_hour`, `period`, `status`) VALUES (NULL, '".$auth_id."', null, CURRENT_TIMESTAMP, '1', '1'); ");
	}

	
}